// import { Post, SyncPost, SyncPostOutside } from '/@/api/linxyun/base/index.ts'
import { warnTime } from './constant.js';
import IFileClient from './file_client_interface.js';
import { httpReqeustApi } from '/@/api/linxyun/base';

const httpReqeust = httpReqeustApi();

export default class FileClient_QN extends IFileClient {
	constructor(fileConfig) {
		super(fileConfig);
	}
	getFileID(fileUrl) {
		if (!fileUrl) {
			console.error('[Error][File]get file id fail, url is empty');
			return null;
		}
		let pos = fileUrl.lastIndexOf('/');
		if (pos < 0) {
			return fileUrl;
		}
		return fileUrl.substr(pos + 1);
	}
	getFileFullUrl(fileID) {
		if (!fileID) {
			return null;
		}
		if (fileID.indexOf('http') === 0) {
			return fileID;
		}

		if (this._fileConfig === null || !this._fileConfig.setting.imgUrl) {
			console.log('[getFileFullUrl]Failed to upload file, no file config info.');
			return null;
		}

		// return this._fileConfig.setting.imgUrl + fileID
		return fileID;
	}

	// 返回full url
	async uploadContent(fileName, content, vm) {
		console.log('[Debug][File][QN]upload file, file: ', fileName, content);
		const formData = await new FormData();
		await formData.append('token', this._fileConfig.postData.token);
		await formData.append('file', content, fileName);
		let res = await httpReqeust.SyncPostOutside(this._fileConfig.setting.uploadUrl, null, formData, (event) => {
			// 监听上传进度
			vm.progressPercent = Number(((event.loaded / event.total) * 100).toFixed(2));
		});
		if (!res || !res.key) {
			console.error('[Error][File][uploadFile][QN]Upload fail, res: ', res);
			return null;
		} else {
			return await this.getFileFullUrl(res.key);
		}
	}

	async deleteFile(url) {
		console.log('[Debug][File][QN]delete file, url: ', url);
		if (!this._fileConfig) {
			console.error('[Error][File][deleteFile][QN]No file config info.');
			return false;
		}

		if (!this._fileConfig.setting.deleteUrl || this._fileConfig.setting.deleteUrl === null) {
			console.error('[Error][File][deleteFile][QN]No deleteUrl.');
			return false;
		}

		let fileID = this.getFileID(url);
		if (!fileID || fileID === '') {
			console.error('[Error][File][QN]delete file, fileid is empty');
			return false;
		}
		console.log('[Debug][File][QN]delete file: ', this._fileConfig.setting.deleteUrl, fileID);
		await httpReqeust.SyncPost(this._fileConfig.setting.deleteUrl, { FileID: fileID });
		return true;
	}

	async checkToken() {
		if (!this._fileConfig || !this._fileConfig.postData) {
			return false;
		}
		if (!(await this.isTokenExpired())) {
			return true;
		}
		let res = await httpReqeust.SyncPost(this._genTokenUrl);
		if (!res || !res.data || res.code !== '0000') {
			console.error('[Error][File][QN]Get token fail.');
			return false;
		}
		this._fileConfig.postData.token = res.data.Token;
		return true;
	}

	async isTokenExpired() {
		if (!this._fileConfig.postData.token) {
			return true;
		}

		const { token } = this._fileConfig.postData;
		const infoStr = await token.split(':')[2];
		const infoObj = JSON.parse(window.atob(infoStr));
		const { deadline } = infoObj;
		const nowTime = await Math.floor(new Date().getTime() / 1000);
		return deadline - warnTime < nowTime;
	}
}
